<template>
  <div class="addProject">
    <div class="addProject-inner">
      <div class="title">
        新建任务
        <i @click="closeFn"></i>
      </div>
      <div class="form">
        <el-form ref="taskForm" :rules="rules" :model="taskForm" label-width="111px" class="demo-ruleForm">
          <el-form-item label="任务标题" prop="taskName">
            <el-input placeholder="请输入任务标题" v-model="taskForm.taskName"></el-input>
          </el-form-item>
          <el-form-item label="所属项目" prop="projectId">
            <el-select placeholder="请选择" v-model="taskForm.projectId">
              <el-option v-for='(item ,index) in projectList' :label="item.shortName" :value="item.id"
                         :key="index"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="设定时间" required>
            <el-col style="float: left;width: 176px;">
              <el-form-item prop="startTimeStamp">
                <el-date-picker type="date" v-model="taskForm.startTimeStamp" placeholder="开始时间" :picker-options="pickerOptionsStart"
                                style="width: 100%;"></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col style="float: left;width: 48px;text-align: center" class="line line-time">至</el-col>
            <el-col style="float: left;width: 176px;">
              <el-form-item prop="limitTimeStamp">
                <el-date-picker type="date" v-model="taskForm.limitTimeStamp" placeholder="截止时间" :picker-options="pickerOptionsEnd"
                                style="width: 100%;"></el-date-picker>
              </el-form-item>
            </el-col>
          </el-form-item>
          <el-form-item label="执行人" prop="workUserId">
            <span class="add-manager" @click="is_show_selectMembers=true"></span>
            <input type="hidden" v-model="taskForm.workUserId" ref="workUserId">
            <span class="select-manager">
              <i v-for="item in selectMembers_list">{{item.name}},</i>
              </span>
          </el-form-item>
          <el-form-item label="定期汇报" prop="reportCycle">
            <input type="hidden" v-model="taskForm.reportCycle" />
            <el-select placeholder="请选择" v-model="reportCycle_type" @visible-change="reportCycleFn">
              <el-option value="0">无</el-option>
              <el-option value="1">自定义</el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="任务描述" prop="des">
            <el-input type="textarea" v-model="taskForm.des" placeholder="请输入任务描述"></el-input>
          </el-form-item>
          <el-form-item>
            <div class="annex-list">
              <vuescroll :ops="ops">
                <ul>
                  <li class="add-annex" @click="addAnnexFn">
                    <i class="add"></i>
                    添加附件
                  </li>
                  <li class="add-annex" v-for="(item,index) in taskForm.upload_picture_list" :key="'img'+index">
                    <div class="img" :style="{backgroundImage: 'url(' + item.url + ')' }"></div>
                    <i class="icon-del" @click="delAnnexImg(index)"></i>
                  </li>
                  <li class="add-annex" v-for="(item,index) in taskForm.upload_video_list" :key="'video'+index">
                    <i class="video-icon"></i>
                    {{item.name}}
                    <i class="icon-del" @click="delAnnexVideo(index)"></i>
                  </li>
                  <li class="add-annex" v-for="(item,index) in taskForm.upload_file_list" :key="'file'+index">
                    <i :class="item.type"></i>
                    {{item.name}}
                    <i class="icon-del" @click="delAnnexFile(index)"></i>
                  </li>
                </ul>
              </vuescroll>
            </div>
            <input ref="upload-file" @change="choose_verify_file" type="file" style="display: none" multiple/>
          </el-form-item>
        </el-form>
      </div>
      <div class="save-btn" @click="submit">派发</div>
    </div>
    <transition name="fade">
      <div class="main-popup" v-if="is_show_selectMembers">
        <select-members @close="closeModal" :title="'选择执行人'" :select="selectMembers_list"
                        @callback="selectMemberCallback"
                        :indexClose="'is_show_selectMembers'"/>
      </div>
    </transition>
    <!--    自定义日期-->
    <customDate v-if="custom_date_data.is_show" :data="custom_date_data" @callback="selectDateCallback"></customDate>
    <!--    自定义日期-->
  </div>
</template>

<script>
  import selectMembers from '@/components/base/selectMembers'; //基本信息詳情
  import customDate from '@/components/customDate'
  import vuescroll from 'vuescroll'

  export default {
    name: "AddTask",
    components: {
      selectMembers, customDate, vuescroll
    },
    props: {
      data: {
        type: Object,
        default: {
          is_show_addProject: false,//是否显示
          projectId: '',//项目id
        }
      }
    },
    data() {
      return {
        reportCycle_type:0,//0：无 1：自定义
        is_show_selectMembers: false,//是否显示执行人框
        ops: {
          vuescroll: {
            wheelDirectionReverse: false,//true：横向滚动，false：竖向滚动
            wheelScrollDuration: 0,//滚动速度
            mode: 'native',
            sizeStrategy: 'percent',
            detectResize: true
          },
          scrollPanel: {
            scrollingX: false,//启用横屏滚动
            scrollingY: true,//关闭竖向滚动
          },
          rail: {
            background: '#e5ebf1',
            opacity: 1,
            size: '6px',
            borderRadius: '6px',
            gutterOfEnds: '10px',//轨道距 x 和 y 轴两端的距离
            gutterOfSide: '0px'//距离容器的距离
          },
          bar: {
            onlyShowBarOnScroll: false,//是否只在滚动时显示bar
            background: '#cbd5df',
            keepShow: true,
            size: '4px',
            minSize: false
          }
        },//滚动配置
        is_show_selectMember: false,//是否显示执行人弹框
        taskForm: {
          upload_picture_list: [], // 临时任务上传图片
          upload_file_list: [], // 临时任务上传文件
          upload_video_list: [], // 临时任务上传视频
          projectId: '',//
          startTimeStamp: '',
          workUserId: '',
          reportCycle: '',
          limitTimeStamp: '',
        },
        rules: {
          taskName: [
            {required: true, message: '请输入任务标题', trigger: 'blur'},
          ],
          projectId: [
            {required: true, message: '请选择所属项目', trigger: 'change'},
          ],
          startTimeStamp: [
            {required: true, message: '请选择开始时间', trigger: 'change'},
          ],
          limitTimeStamp: [
            {required: true, message: '请选择截止时间', trigger: 'change'},
          ],
          workUserId: [
            {required: true, message: '请选择执行人', trigger: 'change'},
          ],
          reportCycle: [
            {required: true, message: '请选择定期汇报', trigger: 'change'},
          ],
        },
        projectList: [],//项目列表
        custom_date_data: {
          type: '1',//1每周 2每月 0 无
          is_show: false,//是否显示
        },//自定义日期数据
        selectMembers_list: [],//执行人列表
        //日期选择不能选择今天之前的日期
        pickerOptionsStart:{
          disabledDate (date) {
            return date && date.valueOf() < Date.now() - 86400000;
          }
        },
        pickerOptionsEnd:{
          disabledDate (date) {
            return date && date.valueOf() < Date.now() - 86400000;
          }
        },
      }
    },
    created() {
      let userInfo = this.$store.state.userInfo;
      let _this = this;
      //获取项目列表
      this.$http.post('/project/project/list', {
        userId: userInfo.userId,
        comId: userInfo.companyId,
        pageNum: 1,
        pageSize: 999,
      }).then(res => {
        if (res.statusCode == 200) {
          this.projectList = res.data.list;
          console.log(this.data.projectId);
          if (this.data.projectId != undefined) {
            this.taskForm.projectId = this.data.projectId;
            console.log(this.taskForm.projectId);
          }
          ;
        } else {
          this.$message.error(res.statusMsg)
        }
      })
    },
    methods: {
      delAnnexImg(index){
        this.taskForm.upload_picture_list.splice(index, 1);
      },
      delAnnexVideo(index){
        this.taskForm.upload_video_list.splice(index, 1);
      },
      delAnnexFile(index){
        this.taskForm.upload_file_list.splice(index, 1);
      },
      // /**
      //  * 拆分文件类型
      //  */
      choose_verify_file() {
        let _this = this,
          upload_file = _this.$refs['upload-file'],
          file_list = upload_file.files;
        for (let item of file_list) {
          //判断是否为付费用户
          if(_this.$store.state.userInfo.payUser != true){
            if(item.type.indexOf('image') == -1){
              _this.$message.error("此功能是高级版专有，请联系商务升级版本，谢谢")
              return;
            }
          }
          let list_length = 1;//文件个数
          //判断文件大小
          if (item.size > _this.upload_file_max_size) {
            _this.$message.error('文件：' + item.name + '太大了，请选择2M以下的附件重新上传');
            continue;
          }

          if (item.type.indexOf('image') !== -1) {
            //文件类型为图片
            list_length += _this.taskForm.upload_picture_list.length;
            if (list_length > 9) {
              _this.$message.error('图片只能上传9个以内，请删除后再上传');
              continue;
            }
            _this.taskForm.upload_picture_list.push({
              'file': item,
              'url': window.URL.createObjectURL(item),
              'name': (item.name || '').intercept_characters()
            })
            console.log(_this.taskForm.upload_picture_list)
          }else if(item.type.indexOf('video') !== -1){
            //文件类型为视频
            list_length += _this.taskForm.upload_video_list.length;
            if (list_length > 2) {
              _this.$message.error('视频只能上传2个以内，请删除后再上传');
              continue;
            }
            _this.taskForm.upload_video_list.push({
              'file': item,
              'url': window.URL.createObjectURL(item),
              'name': (item.name || '').intercept_characters()
            })
          }else {
            //文件类型为其他的
            list_length += _this.taskForm.upload_file_list.length;
            if (list_length > 5) {
              _this.$message.error('附件只能上传5个以内，请删除后再上传');
              continue;
            }
            let suffix_str = item.name.substr(item.name.length - 4, 4),
              _type = suffix_str.indexOf('doc') !== -1 ? 'word-icon' :
                (suffix_str.indexOf('xls') !== -1 ? 'xlsx-icon' : (
                  suffix_str.indexOf('ppt') !== -1 ? 'ppt-icon' : (
                    suffix_str.indexOf('txt') !== -1 ? 'txt-icon' : (
                      suffix_str.indexOf('pdf') !== -1 ? 'pdf-icon' : 'default-icon'
                    )
                  )));
            _this.taskForm.upload_file_list.push({
              'file': item,
              'url': window.URL.createObjectURL(item),
              'type': _type,
              'name': (item.name || '').intercept_characters()
            })
          }
        }
      },
      //添加附件方法
      addAnnexFn() {
        let _this = this;
        this.$refs['upload-file'].click();
      },
      //选择可见范围，隐藏下拉框时触发
      reportCycleFn() {

          if (this.reportCycle_type == 0) {
            //汇报类型为无 0
          } else if (this.taskForm.reportCycle == 7 || this.taskForm.reportCycle == 30 || this.taskForm.reportCycle == 1) {
            //汇报类型为无 每周或者每月 打开自定义日期控件
            this.custom_date_data.is_show = true;
            //一下为日期控件的初始值，编辑任务是重后台获取
            this.custom_date_data.type = '1';//1每周，2每月
            this.custom_date_data.double_cease_month = false;//是否跳过双休，
            this.custom_date_data.holiday = false;//跳过假日
            if (this.custom_date_data.type == 1) {
              //每周
              this.custom_date_data.checkedWeeks = [];//每周选中的天数['2']
              this.custom_date_data.day = [];//重置月的天数
            } else if (this.custom_date_data.type == 2) {
              //每月
              this.custom_date_data.double_cease_month = false;//跳过双休
              this.custom_date_data.checkedWeeks = [];//重置周的天数
              this.custom_date_data.day = [];//汇报的天数 ['17', '20', '周三']
            }
            this.custom_date_data.time = '2019-01-01' + '18:00';//汇报时间
          }
      },
      //选择自定义日期后的回调
      selectDateCallback(data) {
        if (data.type == '1') {
          this.taskForm.reportCycle = 7;//每周
          this.taskForm.ignoreHoliday = data.ignoreHoliday;//是否跳过节假日
          this.taskForm.reportTime = data.reportTime;//汇报时间
          this.taskForm.days = data.days;//汇报时间，数组，若reportCycle为0时可以不传该字段
          this.custom_date_data.is_show = false;//关闭日期控件
        } else {
          this.taskForm.reportCycle = 30;//每月
          this.taskForm.ignoreWeekend = data.ignoreWeekend;//是否跳过周末
          this.taskForm.ignoreHoliday = data.ignoreHoliday;//是否跳过假日
          this.taskForm.reportTime = data.reportTime;//汇报时间
          this.taskForm.days = data.days;//汇报时间，数组，若reportCycle为0时可以不传该字段
          this.custom_date_data.is_show = false;//关闭日期控件
        }
      },
      //关闭人员弹框
      closeModal(res) {
        this[res] = false;
      },
      //选择人员
      selectMemberCallback(data) {
        this.taskForm.workUserId = data;
        this.is_show_selectMembers = false;
        this.selectMembers_list = data;
      },
      //关闭
      closeFn() {
        this.data.is_show = false;
      },
      //保存
      submit() {
        this.$refs['taskForm'].validate((valid) => {
          if (valid) {
            let _this = this;
            let formdata = new FormData();
            formdata.append('companyId', _this.$store.state.userInfo.companyId);//公司id
            formdata.append('createUserId', _this.$store.state.userInfo.userId);//创建任务的人的id 指派人id
            formdata.append('projectId', _this.taskForm.projectId);//项目id
            formdata.append('taskName', _this.taskForm.taskName);//任务名称
            formdata.append('des', _this.taskForm.des);//任务简介
            this.selectMembers_list.map(function (item) {
              formdata.append('workUserIds', item.userId);//执行人id
              formdata.append('workUserIds', item.userId);//执行人id
            });
            formdata.append('reportCycle', _this.taskForm.reportCycle);//汇报时间方式0 ，7 ，30
            if (_this.taskForm.reportCycle == 7 || _this.taskForm.reportCycle == 30) {
              let days = this.taskForm.days;
              days.map(function (item, index) {
                formdata.append('days', item);//定期汇报的周或者月的数据
              });
              formdata.append('reportTime', new Date(_this.taskForm.reportTime).Format("hh:mm"))
            };
            formdata.append('startTimeStamp', new Date(_this.taskForm.startTimeStamp).getTime());//开始时间
            formdata.append('limitTimeStamp', new Date(_this.taskForm.limitTimeStamp).getTime());//结束时间
            formdata.append('ignoreWeekend', _this.taskForm.ignoreWeekend || '');//是否跳过周末
            formdata.append('ignoreHoliday', _this.taskForm.ignoreHoliday || '');//是否跳过节假日
            if(this.taskForm.upload_picture_list.length&&this.taskForm.upload_picture_list.length>0){
              this.taskForm.upload_picture_list.map(function (item) {
                formdata.append('photo', item.file, item.name);
              });
            }
            if(this.taskForm.upload_file_list.length&&this.taskForm.upload_file_list.length>0){
              this.taskForm.upload_file_list.map(function (item) {
                formdata.append('file', item.file, item.name);
              });
            }
            if(this.taskForm.upload_video_list.length&&this.taskForm.upload_video_list.length>0){
              this.taskForm.upload_video_list.map(function (item) {
                formdata.append('video', item.file, item.name);
              });
            }
            this.$http.post('/task/task/insert/createTask', formdata).then(res => {
              if (res.statusCode == 200) {
                this.$message.success('新建任务成功');
                setTimeout(function () {
                  _this.data.is_show = false;
                }, 5000)
              } else {
                this.$message.error(res.statusMsg);
              }
            });
          } else {
            return false
          }
        });

      }
    }
  }
</script>

<style scoped type="text/scss" lang="scss">
  .addProject {
    z-index: 1000;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    position: fixed;
    left: 0;
    top: 0;

    .addProject-inner {
      position: absolute;
      background-color: #FFFFFF;
      border-radius: 6px;
      width: 608px;
      height: 656px;
      left: 0;
      top: 0;
      right: 0;
      bottom: 0;
      margin: auto;
      padding: 32px 32px 0 32px;

      .save-btn {
        position: absolute;
        right: 65px;
        bottom: 24px;
        background-color: #0755db;
        color: #FFFFFF;
        border-radius: 6px;
        width: 88px;
        line-height: 32px;
        text-align: center;
        cursor: pointer;
      }

      > .title {
        line-height: 1.1;
        font-size: 16px;
        color: #454a55;
        position: relative;
        height: 48px;
        font-weight: 600;

        > i {
          background-size: 16px 17px;
          background-position: center;
          background-repeat: no-repeat;
          position: absolute;
          width: 16px;
          height: 17px;
          background-image: url("../../assets/img/close_icon.png");
          top: 0px;
          right: 0px;
          cursor: pointer;
        }
      }

      .form {
        .el-form-item__label {
          padding-right: 16px;
        }

        .cancel-btn, .save-btn {
          display: inline-block;
          border-radius: 6px;
          width: 88px;
          line-height: 32px;
          text-align: center;
          cursor: pointer;
        }

        .save-btn {
          background-color: #0755db;
          color: #FFFFFF;
        }

        .cancel-btn {
          color: #b3c0c9;
        }

        .add-manager {
          position: absolute;
          width: 38px;
          height: 38px;
          background-image: url("../../assets/img/project/add_manager_icon1.png");
          background-size: 38px 38px;
          background-repeat: no-repeat;
          background-position: center;
          cursor: pointer;
        }

        .select-manager {
          padding-left: 50px;
        }

        .add-manager:hover {
          background-image: url("../../assets/img/project/add_manager_icon2.png");
        }

        .annex-list {
          height: 140px;
          padding: 10px 0;

          ul {
            display: flex;
            flex-wrap: wrap;
            padding-top:10px ;
            li {
              width: 100px;
              height: 100px;
              border: 1px solid #EEEEEE;
              text-align: center;
              font-size: 12px;
              padding-top: 50px;
              box-sizing: border-box;
              color: #96A2AA;
              position: relative;
              margin: 0 16px 16px 0;
              border-radius: 6px;
              white-space: nowrap;
              i {
                position: absolute;
                width: 20px;
                height: 20px;
                top: 30px;
                left: 40px;
                background-image: url("../../assets/img/annex/ic_ty.png");
              }

              i.add {
                background-image: url("../../assets/img/annex/ic_add.png");
              }

              i.word-icon {
                background-image: url("../../assets/img/annex/ic_word.png");
              }
              i.pdf-icon {
                background-image: url("../../assets/img/annex/ic_pdf.png");
              }
              i.txt-icon {
                background-image: url("../../assets/img/annex/ic_txt.png");
              }
              i.xlsx-icon{
                background-image: url("../../assets/img/annex/ic_excel.png");
              }
              i.ppt-icon{
                background-image: url("../../assets/img/annex/ic_ppt.png");
              }
              i.video-icon{
                background-image: url("../../assets/img/annex/ic_video.png");
              }
              i.icon-del{
                background-image: url("../../assets/img/annex/ic_delete.png");
                width: 16px;
                height: 16px;
                position: absolute;
                left: 90px;
                top: -5px;
              }
            }

            .add-annex {
              cursor: pointer;
              position: relative;
              >.img{
                position: absolute;
                left: 0;
                top: 0;
                display: block;
                width: 100px;
                height: 100px;
                background-repeat: no-repeat;
                background-size: cover;
                background-position: center;
                border-radius: 6px;
              }
            }
          }

        }
      }
    }
  }
</style>
<style lang="scss" type="text/scss">
  .form {
    .el-form-item__label {
      padding-right: 16px;
    }

    .el-input__inner, .el-textarea__inner {
      width: 400px;
      background-color: #f2f6f9;
      border-color: #f2f6f9;
    }

    .el-date-editor--date, .el-date-editor--time {
      .el-input__inner {
        width: 176px;
      }
    }

    .el-input__inner:focus, .el-textarea__inner:focus {
      background-color: #FFFFFF;
      border-color: #0755db;
    }

    .line-time {
      width: 20px;
    }
  }
</style>
